package com.traffic.api.sms;

import com.taobao.api.ApiException;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.request.AlibabaAliqinFcSmsNumSendRequest;
import com.taobao.api.response.AlibabaAliqinFcSmsNumSendResponse;
import com.traffic.api.entity.SmsInfo;
import com.traffic.api.service.SMSInfoService;
import com.traffic.api.util.RandomUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by churcy on 2017/3/15.
 */
@Component
public class AlidayuSMS {

    private static final String ALIDAYU_SERVER = "http://gw.api.taobao.com/router/rest";
    private static final String ALIDAYU_APPKEY = "23711736";
    private static final String ALIDAYU_SECRET = "d3af14bda528f32c36615b159f7c83ba";

    @Autowired
    private SMSInfoService smsInfoService;

    /**
     * 阿里大于发送注册短信验证码 （后续设置为通用方法）
     *
     * @param mobilePhone
     * @param code
     * @return
     */
    public Map<String, Object> send(String mobilePhone, String code) {
        AlibabaAliqinFcSmsNumSendResponse rsp = null;
        TaobaoClient client = new DefaultTaobaoClient(ALIDAYU_SERVER, ALIDAYU_APPKEY, ALIDAYU_SECRET);
        AlibabaAliqinFcSmsNumSendRequest req = new AlibabaAliqinFcSmsNumSendRequest();
        req.setExtend("123456");
        req.setSmsType("normal");
        //req.setSmsFreeSignName("注册验证");
        req.setSmsFreeSignName("武汉公交");
        //req.setSmsParamString("{\"code\":" + "\"" + ":" + code + "\"" + "," + "\"product\":" + "\"" + "武汉电子公交卡" + "\"}");
        req.setSmsParamString("{\"number\":" + "\"" + code + "." + "\"}");
        req.setRecNum(mobilePhone);
        //req.setSmsTemplateCode("SMS_56600524");
        req.setSmsTemplateCode("SMS_57105261");
        Map<String, Object> result = new HashMap<>();
        try {
            rsp = client.execute(req);
            SmsInfo smsInfo = new SmsInfo();
            smsInfo.setSmsId(code);
            smsInfo.setPhone(mobilePhone);
            smsInfo.setCreateTime(new Date());
            smsInfoService.save(smsInfo);
            result.put("result", rsp.getResult());
            result.put("msg", rsp.getMsg());
            result.put("errorCode", rsp.getErrorCode());
            result.put("subCode", rsp.getSubCode());
            result.put("subMsg", rsp.getSubMsg());
        } catch (ApiException e) {
            e.printStackTrace();
        }
        return result;
    }

}
